package org.example.backend.demos.web.volunteerModule.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.backend.demos.web.Util.JwtTokenUtil;
import org.example.backend.demos.web.volunteerModule.entity.AuditDTO;
import org.example.backend.demos.web.volunteerModule.entity.Volunteer;
import org.example.backend.demos.web.volunteerModule.entity.VolunteerDTO;
import org.example.backend.demos.web.volunteerModule.entity.VolunteerQuery;
import org.example.backend.demos.web.volunteerModule.service.VolunteerService;
import org.example.backend.demos.web.volunteerModule.service.VolunteerStats;
import org.example.backend.demos.web.volunteerModule.service.impl.BatchAuditResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/volunteer")
public class VolunteerController {

    @Autowired
    private VolunteerService volunteerService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 提交志愿者申请
     */
    @PostMapping("/apply")
    public Result<ApplyResult> submitApplication(@RequestBody VolunteerDTO volunteerDTO,
                                                 @RequestHeader("token") String authHeader) {
        Long userId = getCurrentUserId(authHeader);
        String getUsername = Get_username(authHeader);
        Volunteer volunteer = volunteerService.submitApplication(volunteerDTO, userId,getUsername);
        ApplyResult result = new ApplyResult(volunteer.getId(), volunteer.getStatus());

        return Result.success("报名成功", result);
    }

    /**
     * 获取我的报名记录
     */
    @GetMapping("/my-applications")
    public Result<PageResult<Volunteer>> getMyApplications(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status,
            @RequestHeader("token") String authHeader) {

        Long userId = getCurrentUserId(authHeader);
        Page<Volunteer> applications = volunteerService.getUserApplications(userId, page, size, status);

        PageResult<Volunteer> result = convertToPageResult(applications);
        return Result.success(result);
    }

    /**
     * 管理员获取报名详情
     */
    @GetMapping("/applications/{id}")
    public Result<Volunteer> getApplicationDetail(@PathVariable Long id,
                                                  @RequestHeader("token") String authHeader) {
        Long userId = getCurrentUserId(authHeader);
        Volunteer volunteer = volunteerService.getApplicationDetail(id, userId);

        return Result.success(volunteer);
    }

    /**
     * 管理员获取报名列表
     */
    @GetMapping("/admin/applications")
    public Result<PageResult<Volunteer>> getAdminApplicationList(VolunteerQuery query,
                                                                 @RequestHeader("token") String authHeader) {
        verifyAdminRole(authHeader);

        Page<Volunteer> applications = volunteerService.getAdminApplicationList(query);
        PageResult<Volunteer> result = convertToPageResult(applications);

        return Result.success(result);
    }

    /**
     * 管理员审核志愿者申请
     */
    @PostMapping("/admin/applications/{id}/audit")
    public Result<Void> auditApplication(@PathVariable Long id,
                                         @RequestBody AuditDTO auditDTO,
                                         @RequestHeader("token") String authHeader) {
        verifyAdminRole(authHeader);

        volunteerService.auditApplication(id, auditDTO.getStatus(), auditDTO.getAuditRemark());
        return Result.success("审核成功");
    }

    /**
     * 管理员批量审核
     */
    @PostMapping("/admin/applications/batch-audit")
    public Result<BatchAuditResult> batchAuditApplications(
            @RequestBody BatchAuditDTO batchAuditDTO,
            @RequestHeader("token") String authHeader) {
        verifyAdminRole(authHeader);

        BatchAuditResult result = volunteerService.batchAuditApplications(
                batchAuditDTO.getApplicationIds(),
                batchAuditDTO.getStatus(),
                batchAuditDTO.getAuditRemark()
        );

        return Result.success("批量审核成功", result);
    }

    /**
     * 获取报名统计
     */
    @GetMapping("/admin/stats")
    public Result<VolunteerStats> getVolunteerStats(@RequestHeader("token") String authHeader) {
        verifyAdminRole(authHeader);
        VolunteerStats stats = volunteerService.getVolunteerStats();
        return Result.success(stats);
    }

    // 辅助方法
    private PageResult<Volunteer> convertToPageResult(Page<Volunteer> page) {
        List<Volunteer> list = page.getRecords().stream()
                .collect(Collectors.toList());

        return new PageResult<>(
                list,
                page.getTotal(),
                (int) page.getCurrent(),
                (int) page.getSize()
        );
    }

    // 从JWT token获取当前用户ID
    private Long getCurrentUserId(String authHeader) {
        log.info(authHeader);
        if (authHeader == null ) {
            throw new RuntimeException("未提供有效的认证信息");
        }

        return jwtTokenUtil.getUserIdFromToken(authHeader);
    }

    // 验证管理员角色
    private void verifyAdminRole(String authHeader) {
        log.info(authHeader);
        if (authHeader == null ) {
            throw new RuntimeException("未提供有效的认证信息");
        }
        if (!jwtTokenUtil.isAdmin(authHeader)) {
            throw new RuntimeException("无权限访问");
        }
    }
    //获取用户名
    private String Get_username(String authHeader) {
        log.info(authHeader);
        if (authHeader == null) {
            return "";
        }
        return jwtTokenUtil.getUsernameFromToken(authHeader);
    }
}